<template>
  <div class="tempwrapper">
    <!-- <div class="orderHeader" style="margin:5px 0px 0px 0px">
      <div class="orderSearch">
        <el-form ref="form" :model="searchParams" :inline="true" style="float:left">
          <el-form-item label="编号" size="mini">
            <el-input v-model="searchParams.serial_number" clearable placeholder="请填写编号进行搜索" />
          </el-form-item>
          <el-form-item size="mini">
            <el-button type="primary" icon="el-icon-search" @click="handleSearch">查询</el-button>
            <el-button type="primary" plain icon="el-icon-refresh" @click="handleReset">重置
            </el-button>
          </el-form-item>

        </el-form>
      </div>
    </div>
    <div class="actions">
      <div class="left">
        <el-button v-permission="'company_thermometer_create'" type="primary" style="margin-bottom:10px" plain size="mini"
          @click="handleAddMaterial(MATERIAL.THERMOMETER)">添加温度计</el-button>
      </div>
      <div class="right">
        <el-pagination :current-page="paginations.pageIndex" :page-sizes="paginations.pageSizes"
          :page-size="paginations.pageSize" :layout="paginations.layout" :total="paginations.total"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </div>
    <el-table id="thermometer" ref="multipleTable" class="thermo" stripe :data="thermometerData" border
      tooltip-effect="dark" style="width: 100%" :row-key="(item) => item.id" @row-click="handleClickTableRow"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" :reserve-selection="true" width="55"> </el-table-column>
      <el-table-column property="name" label="设备名称" width="150"></el-table-column>
      <el-table-column property="serial_number" width="200" label="设备编号"></el-table-column>
      <el-table-column property="power" label="电量"></el-table-column>
      <el-table-column property="temp_measure_range" label="温度区间">
      </el-table-column>
      <el-table-column property="thermometer_type" label="传输类型">
        <template slot-scope="scope">
          {{ typeArr[scope.row.thermometer_type] }}
        </template>
      </el-table-column>
      <el-table-column prop="manufacturer" label="生产厂家" width="240"></el-table-column>
      <el-table-column property="status" label="启用状态" width="80">
        <template slot-scope="scope">
          {{ statusArr[scope.row.status] }}
        </template>
      </el-table-column>
    </el-table> -->
    <div class="paste" v-if="isEdit">
      <el-input type="textarea" placeholder="请粘贴或输入温度计编号（多个温度计用逗号或空格分隔），点击“识别”自动绑定" v-model="text"
        :autosize="{ minRows: 3, maxRows: 5 }">
      </el-input>
      <div class="paste-btn">
        <div class="btn" @click="resolveText(false)">识别并绑定</div>
      </div>
    </div>

    <el-form v-model="ruleForm" label-width="100" style="padding-top: 20px">
      <el-row :gutter="24" v-if="isEdit">
        <el-col :span="9">
          <el-form-item label="温度计绑定" prop="thermometerIds">
            <el-select style="width: 220px" multiple clearable @change="changeSelect" v-model="ruleForm.thermometerIds"
              filterable remote placeholder="请选择" :remote-method="remoteMethod" :disabled="!isEdit">
              <el-option v-for="item in thermometerData" :key="item.id" :label="item.serial_number" :value="item.id + ''">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="9">
          <el-form-item label="开始采集时间" prop="start_time">
            <el-date-picker style="width: 220px" popper-class="pos-right" v-model="ruleForm.start_time" type="datetime" placeholder="选择日期时间"
              value-format="timestamp">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-table v-if="!isEdit" id="thermometer" ref="multipleTable" class="thermo" stripe :data="checkedBind" border tooltip-effect="dark"
      style="width: 100%;margin-bottom: 10px;" @selection-change="handleSelectionChange">
      <el-table-column type="index" width="55"> </el-table-column>
      <el-table-column property="thermometer_no" label="温度计编号"></el-table-column>
      <el-table-column property="incubator_no" label="保温箱编号">
      </el-table-column>

      <el-table-column property="status" label="附件" width="120">
        <template slot-scope="scope">
          <el-image v-if="scope.row.annex" style="width: 100px; height: 50px;cursor: pointer;" :src="scope.row.annex"
            fit='cover' @click.native="handlePreview(scope.row.annex)">
          </el-image>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :visible.sync="dialogImageVisible" append-to-body>
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
    <div style="text-align: right">
      <el-button id="bind_cancel" @click="handleClickClose">取消</el-button>
      <el-button id="bind_ok" type="primary" @click="handleClickOk">确定</el-button>
    </div>
    <MaterialAdd :type="materialType" @ok="handleMaterialAddOk" @close="handleCloseMaterialDialog"
      :dialogVisible="materialDialogVisible">
    </MaterialAdd>
    <el-dialog title="提示" append-to-body :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
      <div>
        检测到以下温度计不在系统，请确认温度计编号是否正确
        <ol>
          <li :key="index" v-for="(item, index) in noExistList">
            {{ index + 1 }}、{{ item }}
          </li>
        </ol>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary"  @click="handleNoCreate">确定</el-button>
        <!-- <el-button type="primary" @click="handleAutoCreate">是的</el-button> -->
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { QueryThermometer } from "../../../api/information";
import { ThermometerBindFn, thermometerIdentify } from "@/api/waybill";
import { Message, MessageBox } from "element-ui";
import { timestamp10 } from "@/utils/mUtils";
import { MATERIAL } from "@/page/waybill/constants";
import MaterialAdd from "./materialAdd.vue";

export default {
  name: "temperatureBind",
  components: { MaterialAdd },
  props: ["time", "record", "checkedBind", "instance", "maxLength"],
  data() {
    return {
      thermometerData: [],
      checkedTemperatures: [],
      typeArr: ["实时", "离线"],
      statusArr: ["启用", "禁用"],
      ruleForm: {
        start_time: "",
        thermometerIds: [],
      },
      paginations: {
        pageIndex: 1, // 当前位于哪页
        pageSize: 20, // 1页显示多少条
        pageSizes: [10, 20, 50, 100], //每页显示多少条
        total: 200,
        layout: "total, sizes, prev, pager, next, jumper", // 翻页属性
      },
      searchParams: {
        serial_number: "",
      },
      MATERIAL: MATERIAL,
      materialType: "",
      materialDialogVisible: false,
      text: "",
      noExistList: [],
      existList: [],
      dialogVisible: false,
      isEdit: true,
      dialogImageUrl: '',
      dialogImageVisible: false,
    };
  },
  async created() {
    // console.log(this.time, "this.time");
    this.ruleForm.start_time = this.time * 1000 || Date.now();
    this.getThermometerList();
  },

  watch: {
    checkedBind: {
      deep: true,
      immediate: true,
      handler: function (newValue, oldValue) {
        console.log(newValue,'newValue')
        if (Array.isArray(newValue) && newValue.length === 0) return;
        this.initCheck();
      },
    },
  },
  methods: {
    handlePreview(url) {
      this.dialogImageUrl = url;
      this.dialogImageVisible = true;
    },
    handleAutoCreate() {
      this.resolveText(true);
      this.text = "";
    },
    // 改变下拉及绑定的值
    handleNoCreate() {
      this.changeData();
      this.text = "";
    },
    handleClose() {
      this.handleNoCreate();
    },
    changeData() {
      const data = this.existList;
      this.dialogVisible = false;
      this.changeThermometerData(data);
      const ids = this.ruleForm.thermometerIds.concat(
        data.map((item) => item.id)
      );
      this.ruleForm.thermometerIds = Array.from(new Set(ids));
    },
    resolveText(isAutoCreate = false) {
      thermometerIdentify({
        thermometer_nos: this.text,
        is_auto_create: isAutoCreate,
      }).then((res) => {
        this.existList = res.data.list || [];
        this.noExistList = res.data.not_exist_list || [];
        if (this.noExistList.length > 0) {
          this.dialogVisible = true;
        } else {
          this.changeData();
        }
      });
    },
    changeSelect(val) {
      // console.log(val, "cva");
    },
    // 获取当前选中的【{name,value}】
    getValues() {
      const data = this.thermometerData.filter((item) =>
        this.ruleForm.thermometerIds.includes(item.id)
      );
      return data;
    },
    // 数组根据id去重
    unique(arr) {
      let res = new Map();
      for (let i of arr) {
        if (!res.has(i.id)) {
          res.set(i.id, i);
        }
      }
      const uniArr = [...res.values()];
      return uniArr;
    },
    changeThermometerData(data) {
      const existData = this.getValues();
      this.thermometerData = this.unique(data.concat(existData));
    },
    remoteMethod(val) {
      // console.log(val, "vaaaaaaa");
      this.getThermometerList(val);
    },
    handleClickTableRow(row) {
      this.$refs.multipleTable.toggleRowSelection(row);
    },
    handleAddMaterial(materialType) {
      // console.log(materialType);
      this.materialType = materialType;
      this.materialDialogVisible = false;
      setTimeout(() => {
        this.materialDialogVisible = true;
      }, 10);
    },
    handleCloseMaterialDialog() {
      this.materialDialogVisible = false;
    },
    handleMaterialAddOk() {
      this.paginations.pageIndex = 1;
      this.getThermometerList();
    },
    // 每页条数改变
    handleSizeChange(val) {
      this.paginations.pageSize = val;
      this.getThermometerList();
    },
    // 当前页改变
    handleCurrentChange(val) {
      this.paginations.pageIndex = val;
      this.getThermometerList();
    },
    handleSearch() {
      this.paginations.pageIndex = 1;
      this.getThermometerList();
    },
    handleReset() {
      this.searchParams = {};
      this.paginations.pageIndex = 1;
      this.getThermometerList();
    },
    getThermometerList(val = "") {
      QueryThermometer({
        page: 1,
        page_size: 30,
        serial_number: val,
      }).then((res) => {
        let data = res.data.list || [];
        data = data.map((item) => ({
          id: item.id + "",
          serial_number: item.serial_number,
        }));
        this.changeThermometerData(data);
        // 第一次watch拿不到 thermometerData，在这需绑定一下
        // this.initCheck();
        // this.paginations.total = res.data.pagination.total;
      });
    },
    handleSelectionChange(checked) {
      this.checkedTemperatures = checked.map((item) => {
        return {
          thermometer_id: item.id + "",
          thermometer_no: item.serial_number,
        };
      });
    },
    handleClickClose() {
      MessageBox.close(true);
    },
    // 已经绑定的温度计做回显
    initCheck() {
      // this.$nextTick(() => {
      //   for (const item of this.thermometerData) {
      //     if (this.checkedBind && this.checkedBind.find(t => Number(t.thermometer_id) === item.id)) {
      //       this.$refs.multipleTable.toggleRowSelection(item, true);
      //     }
      //   }
      // });
      this.thermometerData = this.checkedBind.map((item) => {
        return { id: item.thermometer_id, serial_number: item.thermometer_no };
      });
      this.ruleForm.thermometerIds = this.checkedBind.map(
        (item) => item.thermometer_id
      );
      // 都没有保温箱号,能编辑
      this.isEdit = this.checkedBind.every(item =>{
        console.log(item.incubator_no === '')
       return !item.incubator_no
      });
    },
    handleClickOk() {
      const start_time = timestamp10(this.ruleForm.start_time);
      if (this.maxLength) {
        if (this.checkedTemperatures.length > this.maxLength) {
          this.$message({
            type: "warning",
            message: "只支持单个温度计绑定",
          });
          return;
        }
      }
      // this.checkedTemperatures = this.thermometerData.map((item) => {
      //   return { thermometer_id: item.id + '', thermometer_no: item.serial_number };
      // });
      // this.checkedTemperatures = this.checkedTemperatures.map(item => {
      //   item.start_time = start_time;
      //   return item;
      // });
      // const checkedData = this.thermometerData.filter(item => this.ruleForm.thermometerIds.includes(item.id));
      // this.checkedTemperatures = checkedData.map(item => {
      //   item.start_time = start_time;
      //   return item;
      // });
      this.checkedTemperatures = [];
      // this.thermometerData.forEach(item => {
      //   if (this.ruleForm.thermometerIds.includes(item.id)) {
      //     this.checkedTemperatures.push({ thermometer_id: item.id + '', thermometer_no: item.serial_number, start_time: item.start_time });
      //   }
      // });
      this.ruleForm.thermometerIds.forEach((id) => {
        const existItem = (this.checkedBind||[]).find((item) => item.thermometer_id === id);
        // 原本的
        if (existItem) {
          this.checkedTemperatures.push({
            ...existItem,
            start_time: start_time,
          });
          // 新添加的
        } else {
          const item = this.thermometerData.find((item) => item.id === id);
          if (item) {
            this.checkedTemperatures.push({
              thermometer_id: item.id + "",
              thermometer_no: item.serial_number,
              start_time: start_time,
            });
          }
        }

      });
      this.record &&
        this.record({
          start_time,
          checkedTemperatures: this.checkedTemperatures,
        });
      this.handleClickClose();
      // ThermometerBindFn(
      //   {
      //     "waybill_id": this.waybill_id + '',
      //     "thermometer_id": this.checkedTemps[0] + '',
      //     "bind_type": "3",
      //     "bind_node": this.node + ''
      //   }
      // ).then(res => {
      //   if (res.code === 10000) {
      //     this.$message({
      //       message: "新建成功",
      //       type: "success",
      //     });
      //     this.handleClickClose()
      //   }
      // })
    },
  },
};
</script>
<style lang="scss" scoped>
.paste {
  position: relative;

  .paste-btn {
    position: absolute;
    bottom: 5px;
    right: 10px;

    .btn {
      --hover-shadows: 16px 16px 33px #88d1f6, -16px -16px 33px #88d1f6;
      --accent: #409eff;
      font-size: 12px;
      letter-spacing: 0.1em;
      border: none;
      border-radius: 1.1em;
      background-color: var(--primaryColor);
      color: white;
      padding: 3px 10px;
      transition: box-shadow ease-in-out 0.3s, background-color ease-in-out 0.1s,
        letter-spacing ease-in-out 0.1s, transform ease-in-out 0.1s;
    }

    .btn:hover {
      // box-shadow: var(--hover-shadows);
    }

    .btn:active {
      // box-shadow: var(--hover-shadows),
      //   var(--accent) 0px 0px 5px 5px;
      background-color: var(--accent);
      transform: scale(0.95);
    }
  }
}

.thermo {
  max-height: 50vh;
  overflow-y: scroll;
  border-bottom: solid 1px #ebeef5;
}

.thermo.el-table::before {
  height: 0px;
}

.actions {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  width: 100%;
  background-color: #fff;
}

.orderHeader {
  margin-top: 5px;
  background-color: #fff;

  .orderSearch {
    form {
      ::v-deep .el-form-item__label {
        font-size: 12px;
      }

      .el-textarea {
        width: 135px;
      }
    }
  }
}

</style>
<style lang="scss">
.tempwrapper {
  width: 500px;
  padding-top: 20px;
}

.sure {
  z-index: 3333 !important;
}
.el-picker-panel.pos-right{
  margin-left: 230px;
  margin-top: 200px;
  .popper__arrow{
    display: none;
  }
}
</style>